﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.ComponentModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using Microsoft.Xna.Framework.Graphics.PackedVector;

namespace ContentPipelineExtension
{
    [ContentProcessor]
    [DesignTimeVisible(false)]
    class DiffSpecTextureProcessor : ContentProcessor<TextureContent, TextureContent>
    {
        public override TextureContent Process(TextureContent input,
            ContentProcessorContext context)
        {
            // divide each color by PI (as instructed by the shading model) 
            // at build time instead of in the shader.
            input.ConvertBitmapType(typeof(PixelBitmapContent<Vector4>));

            foreach (MipmapChain mipmapChain in input.Faces)
            {
                foreach (PixelBitmapContent<Vector4> bitmap in mipmapChain)
                {
                    for (int x = 0; x < bitmap.Width; x++)
                    {
                        for (int y = 0; y < bitmap.Height; y++)
                        {
                            Vector4 encoded = bitmap.GetPixel(x, y);
                            bitmap.SetPixel(x, y,
                                new Vector4(
                                    encoded.X / (float)Math.PI,
                                    encoded.Y / (float)Math.PI,
                                    encoded.Z / (float)Math.PI,
                                    encoded.Z));
                        }
                    }
                }
            }

            input.ConvertBitmapType(typeof(PixelBitmapContent<NormalizedByte4>));

            input.GenerateMipmaps(false);
            return input;
        }
    }
}
